package com.cg.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;
import java.util.Optional;

@ControllerAdvice
public class HttpStatusCodeAdvice implements ResponseBodyAdvice {

    /**
     * 指定是否进行拦截
     * @param returnType the return type
     * @param converterType the selected converter type
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //取出后端响应结果 修改http状态码
        if(body != null) {
            if(body instanceof String){

            }else{
                Optional.ofNullable((Map<Object,Object>)body)
                        .ifPresent(o -> {
                            int code = (int)o.get("code");
                            response.setStatusCode(HttpStatus.valueOf(code));
                        });
            }
        }
        return body;
    }
}
